<template>
    <div>
        <JsonSchemaPushSetting
            ref="pushSetting"
            @handleGetEditorJson="handleGetEditorJson"
            @handleSaveEditorJson="handleSaveEditorJson"
            @handleSaveJsonFile="handleSaveJsonFile"
        />

        <div class="container">
            <div class="left-panel">
                <JsonSchemaHeader />
                <div class="editor-container">
                    <JsonSchemaEditor
                        ref="jsonSchemaEditor"
                        class="schema"
                        :value="tree"
                        disabled-type
                        lang="zh_CN"
                        custom
                    />
                </div>
                <div class="preview-controls">
                    <a-tag color="blue"> 变量数量: {{ variableCount }} </a-tag>
                    <div class="spacer" />
                    <a-button type="primary" @click="togglePreview">json预览</a-button>
                    <div class="spacer-button" />
                    <a-button type="primary" @click="handleJsonAddRootNode">
                        新增根节点
                    </a-button>
                </div>
            </div>
            <div v-show="showPreview" class="preview-container">
                <div class="preview-header">
                    <h3>JSON预览</h3>
                    <a-button type="link" @click="togglePreview">关闭</a-button>
                </div>
                <div class="preview-content">
                    <codemirror
                        ref="jsonEditor"
                        v-model="importJson"
                        class="code"
                        :read-only="false"
                        :options="{
                            lineNumbers: true,
                            lineWrapping: true,
                        }"
                    />
                </div>
            </div>
        </div>
        <!-- <a-modal v-model="visible" title="预览json" width="800px" height="600x">
            <div class="code-container">
                <codemirror
                    ref="jsonEditor"
                    v-model="importJson"
                    class="code"
                    :read-only="false"
                    :options="{ lineNumbers: true }"
                />
            </div>
            <template #footer>
                <a-button type="primary" @click="visible = false">关闭</a-button>
            </template>
        </a-modal> -->
    </div>
</template>

<script>
// EdgeTabManager全局函数已通过统一的TabManager注册，无需额外导入
var app = require('../../../../package.json')
import codemirror from './components/Codemirror.vue'
import 'codemirror/mode/javascript/javascript.js'
import 'codemirror/addon/lint/lint.js'
import 'codemirror/addon/lint/json-lint.js'
import GenerateSchema from 'generate-schema'
import JsonSchemaHeader from './components/JsonSchemaHeader.vue'
import JsonSchemaPushSetting from './components/JsonSchemaPushSetting.vue'
import _ from 'lodash'
import { traverseJSON, removeExtraKeyWithObj } from './components/JsonManager'

export default {
    name: 'JsonSchemaEditorApp',
    components: {
        codemirror,
        JsonSchemaHeader,
        JsonSchemaPushSetting
    },
    props: {
        mode: {
            type: String,
            default: 'publish',
            validator: value => ['publish', 'subscribe'].includes(value)
        },
        tabInfo: {
            type: Object,
            required: true,
            validator: value => {
                return value.name && value.index && value.type
            }
        },
        configFile: {
            type: String,
            default: 'MqttMsgFormat.json'
        },
        originFile: {
            type: String,
            default: 'JsonDemoOrigin.json'
        }
    },
    data() {
        return {
            version: app.version,
            importJson: '',
            visible: false,
            variableCount: 0,
            tree: {
                root: {
                    type: 'object',
                    title: '',
                    properties: {}
                }
            },
            showPreview: false
        }
    },
    computed: {
        jsonStr: {
            get: function() {
                return JSON.stringify(this.tree, null, 2)
            },
            set: function(newVal) {
                this.tree = JSON.parse(newVal)
            }
        },
        fileName() {
            return `tab${this.tabInfo.index}_${this.tabInfo.type}.json`
        },
        filePayloadName() {
            // 判断是发送还是订阅
            if (this.tabInfo.type === 'pub') {
                return `pub${this.tabInfo.index}.json`
            } else {
                return `sub${this.tabInfo.index}.json`
            }
        }
    },
    watch: {
        tree: {
            handler(newTree) {
                this.variableCount = this.countVariables(newTree)
                console.log('fileName ' + this.fileName)
                if (this.showPreview) {
                    this.updatePreview()
                }
            },
            deep: true
        }
    },
    mounted() {
        this.variableCount = this.countVariables(this.tree)
    },
    methods: {
        countVariables(obj) {
            let count = 0
            if (typeof obj === 'object' && obj !== null) {
                if (Array.isArray(obj)) {
                    for (let item of obj) {
                        count += this.countVariables(item)
                    }
                } else {
                    for (let key in obj) {
                        if (Object.prototype.hasOwnProperty.call(obj, key)) {
                            if (key === 'name' && obj[key] !== undefined && obj[key] !== '') {
                                count++
                            }
                            count += this.countVariables(obj[key])
                        }
                    }
                }
            }
            return count
        },
        handleImportJson() {
            const t = GenerateSchema.json(JSON.parse(this.importJson))
            delete t.$schema
            this.tree.root = t
            this.visible = false
        },
        async handleSaveEditorJson() {
            console.log('handleSaveEditorJson ')
        },
        async handleGetEditorJson() {
            console.log('handleGetEditorJson ')
        },

        setOriginFileContent(data) {
            this.tree = JSON.parse(data)
        },

        handleJsonPreview() {
            this.visible = true
            this.updatePreview()
        },
        updatePreview() {
            let jsonStringObj = _.cloneDeep(this.tree.root.properties)
            removeExtraKeyWithObj(jsonStringObj)
            traverseJSON(jsonStringObj, true)
            const jsonData = JSON.stringify(jsonStringObj, null, 2)
            this.importJson = jsonData
        },
        handleJsonAddRootNode() {
            this.$refs.jsonSchemaEditor.addChild()
        },
        isArrayItem(data, level) {
            if (level === 1) return false

            const parentKey = Object.keys(data)[0]
            const parentValue = data[parentKey]

            return Array.isArray(parentValue) && !isNaN(parseInt(parentKey))
        },

        async handleSaveJsonFile() {
            console.log('handleSaveJsonFile ')
        },

        getJsonFileContent() {
            let jsonStringObj = _.cloneDeep(this.tree.root.properties)
            removeExtraKeyWithObj(jsonStringObj)
            traverseJSON(jsonStringObj, false)
            const jsonData = JSON.stringify(jsonStringObj)
            return { data: jsonData, fileName: this.filePayloadName }
        },

        getJsonOriginFileContent() {
            let jsonStringRootObj = _.cloneDeep(this.tree)
            jsonStringRootObj = JSON.stringify(jsonStringRootObj)
            return { data: jsonStringRootObj, fileName: this.fileName }
        },

        togglePreview() {
            this.showPreview = !this.showPreview
            if (this.showPreview) {
                this.updatePreview()
            }
        }
    }
}
</script>
<style scoped>
* {
    padding: 0;
    margin: 0;
    box-sizing: border-box;
}
.title {
    text-align: center;
    font-size: 40px;
    font-weight: bold;
    height: 100px;
    line-height: 100px;
}
.version {
    font-size: 16px;
}
.desc {
    padding: 20px;
    width: 80vw;
    min-width: 800px;
    margin: auto;

    /* padding: 0 3em; */
    font-size: 1.2em;
}
.container {
    display: flex;
    padding: 20px;
    width: 80vw;
    min-width: 1100px;
    justify-content: center;
    height: calc(100vh - 0px);
    margin: auto;
}
.left-panel {
    width: 65%;
    display: flex;
    flex-direction: column;
    height: 100%;
    position: relative;
}
.left-panel > :first-child {
    position: sticky;
    top: 0;
    z-index: 10;
    background-color: #fff;
    padding-bottom: 10px;
}
.code-container {
    max-height: 600px;
    overflow: auto;
}
.editor-container {
    flex: 1;
    display: flex;
    flex-direction: column;
    overflow: hidden;
    min-height: 0;
}
.schema {
    margin-left: 20px;
    width: 100%;
    height: 100%;
    overflow-y: auto;
    overflow-x: hidden;
}
::v-deep .CodeMirror {
    height: 100% !important;
}
.preview-controls {
    position: sticky;
    bottom: 0;
    z-index: 10;
    background-color: #fff;
    margin: 0;
    padding: 15px 20px;
    width: 100%;
    min-width: auto;
    display: flex;
    align-items: center;
    border-top: 1px solid rgba(0, 0, 0, 0.1);
}

/* 为 .preview-controls 内的元素添加特定样式来覆盖全局重置 */
.preview-controls .ant-btn {
    margin: 0 4px !important;
    padding: 4px 15px !important;
}
.preview-controls .ant-tag {
    margin: 0 !important;
    padding: 0 7px !important;
}
.preview-controls .spacer {
    margin: 0 !important;
    padding: 0 !important;
}
.preview-controls .spacer-button {
    margin: 0 !important;
    padding: 0 !important;
}
.spacer {
    flex: 7;
}
.spacer-button {
    flex: 1;
}
.preview-container {
    width: 35%;
    margin-left: 20px;
    border: 1px solid rgba(0, 0, 0, 0.1);
    border-radius: 8px;
    display: flex;
    flex-direction: column;
    height: calc(100vh - 370px);
    position: sticky;
    top: 20px;
    align-self: flex-start;
}
.preview-header {
    padding: 12px;
    border-bottom: 1px solid rgba(0, 0, 0, 0.1);
    display: flex;
    justify-content: space-between;
    align-items: center;
}
.preview-header h3 {
    margin: 0;
}
.preview-content {
    flex: 1;
    overflow: hidden;
    padding: 12px;
    height: calc(100% - 57px);
}
.preview-content .code {
    height: 100%;
}
.preview-content .CodeMirror {
    height: 100% !important;
    font-size: 14px;
    line-height: 1.5;
}
.preview-content .CodeMirror-scroll {
    min-height: 100%;
}
</style>
